//
//  BaseViewController.swift
//  FastDevelop
//
//  Created by IOS1 on 2025/6/26.
//

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        
        // 清空标题
        navigationItem.title = ""
        // 隐藏导航栏（整个导航栏会消失）
        navigationController?.navigationBar.isHidden = true
    }
    
    func showToast(_ message: String) {

        GlobalTool.shared.showToast(message: message)
    }

}

//dayily Data
extension BaseViewController {
    
    func loadDailyLogs(forKey key: String) -> [DailyLog] {
        if let savedData = UserDefaults.standard.data(forKey: key),
           let decoded = try? JSONDecoder().decode([DailyLog].self, from: savedData) {
            return decoded
        }
        return []
    }

    func appendEntry(_ entry: Entry, toDate date: String, forKey key: String) {
        // 1. 先从 UserDefaults 读取整个 DailyLog 数组
        var logs = loadDailyLogs(forKey: key)

        // 2. 查找是否已经存在这个日期的 DailyLog
        if let index = logs.firstIndex(where: { $0.date == date }) {
            // 存在：在已有的 data 数组中追加
            logs[index].data.append(entry)
        } else {
            // 不存在：创建一个新的 DailyLog
            let newLog = DailyLog(date: date, data: [entry])
            logs.append(newLog)
        }

        // 3. 存回 UserDefaults
        if let encoded = try? JSONEncoder().encode(logs) {
            UserDefaults.standard.set(encoded, forKey: key)
        }
    }

    func searchDailyLogs(containing keyword: String, forKey key: String) -> [DailyLog] {
        let logs = loadDailyLogs(forKey: key)
        let trimmedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines)

        // ✅ 关键词为空，返回全部 logs
        guard !trimmedKeyword.isEmpty else {
            return logs
        }

        let lowercaseKeyword = trimmedKeyword.lowercased()

        return logs.compactMap { log in
            let matchedEntries = log.data.filter { $0.content.lowercased().contains(lowercaseKeyword) }
            return matchedEntries.isEmpty ? nil : DailyLog(date: log.date, data: matchedEntries)
        }
    }


}


class GlobalTool: NSObject {
    
    static let shared = GlobalTool()
    
    func showToast(message: String) {
        
        if let window = UIApplication.window {
            window.makeToast(message, duration: 2.0, position: .bottom)
        }
    }
}
